package data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Observable;

public class Connection extends Observable implements Runnable {

	public static final int OPEN = 0;
	public static final int ERROR = 1;
	public static final int COMPLETE = 2;
	public static final int CANCELLED = 3;

	public static final String STATUSES[] = { "Open", "Error", "Complete", "Cancelled" };

	private URL url;
	private int status;
	private long startTime = 0;
	public static final boolean proxyRequired = false;

	public Connection(URL url) {
		this.url = url;
		status = OPEN;
		open();
	}

	public String getUrl() {
		return url.toString();
	}

	public int getStatus() {
		return status;
	}

	public void cancel() {
		status = CANCELLED;
		stateChanged();
	}

	private void error() {
		status = ERROR;
		stateChanged();
	}

	private void open() {
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		try {
			URLConnection uc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				Thread.sleep(1);
			}

			in.close();
			stateChanged();
			if (status == OPEN) {
				status = COMPLETE;
				stateChanged();
			}
		} catch (Exception e) {
			e.printStackTrace();
			error();
		}
	}

	private void stateChanged() {
		setChanged();
		notifyObservers();
	}
}
